#include "connection.h"
#include <boost\bind.hpp>
#include "connection_manage.h"

#include "log.h"

namespace jump
{
	namespace client
	{

		Connection::Connection(boost::asio::io_service& arg_ioService,Connection_Manage& arg_conn_mgr)
			:socket_(arg_ioService),
			connectionMgr_(arg_conn_mgr)
		{

		}

		boost::asio::ip::tcp::socket& Connection::socket()
		{
			return socket_;
		}

		void Connection::start()
		{
			strncpy(buf_,"MSG",MAX_LENGTH);

			boost::asio::async_write(socket_, boost::asio::buffer(buf_,MAX_LENGTH),
				boost::bind(&Connection::handle_write, this,
				boost::asio::placeholders::error));
		}

		void Connection::stop()
		{
			socket_.close();
		}


		void Connection::handle_write(const boost::system::error_code& arg_err)
		{
			if (!arg_err)
			{
				//LOG_INFO("WROTE");

				socket_.async_read_some(boost::asio::buffer(buf_,MAX_LENGTH),
					boost::bind(&Connection::handle_read, shared_from_this(),
					boost::asio::placeholders::error));

			}
			else
			{
				LOG_ERR("Erro in handle write",arg_err.message());
				connectionMgr_.stop(shared_from_this());
			}
		}

		void Connection::handle_read(const boost::system::error_code& arg_err)
		{
			if(!arg_err)
			{
				//LOG_INFO(buf_);

				/*socket_.async_read_some(boost::asio::buffer(buf_,MAX_LENGTH),
				boost::bind(&Connection::handle_read, shared_from_this(),
				boost::asio::placeholders::error));*/
				boost::asio::async_write(socket_,boost::asio::buffer(buf_,MAX_LENGTH),
					boost::bind(&Connection::handle_write, shared_from_this(),
					boost::asio::placeholders::error));
			}else {
				LOG_ERR("Erro in handle read",arg_err.message());
				connectionMgr_.stop(shared_from_this());
			}

		}
	}//namespace client
}//namespace jump

